layui.config({
    base: '/layuiadmin/'
}).extend({
    index: 'lib/index'// 主入口模块,
    ,treetable: 'treetable-lay/treetable'
}).use(['table', 'index','treetable'], function () {
    var $ = layui.jquery;
        var table = layui.table;
        var admin = layui.admin
        var treetable = layui.treetable;

          // 渲染表格
        var renderTable = function () {
            // 渲染表格
            layer.load(2);
            admin.req({
                type:"GET",
                url:"/api/admin/menu/listALL",     
                dataType:"json",
                success:function(res){
                    treetable.render({
                        treeColIndex: 1,
                        treeSpid: 1,
                        treeIdName: 'id',
                        treePidName: 'parentId',
                        treeDefaultClose: true,
                        elem: '#auth-table',
                        data: res.data,
                        page: false,
                        cols: [[
                            {type: 'numbers'},
                            {field: 'name', minWidth: 200, title: '名称'},
                            {field: 'permission', title: '权限标识'},
                            {field: 'href', title: '菜单地址'},
                            {field: 'sort',  align: 'center', title: '排序号'},
                            {
                                field: 'hasshow', width: 80, align: 'center', templet: function (d) {
                                    if (d.hasShow == 1) {
                                        return '<span class="layui-badge layui-bg-gray">显示</span>';
                                    } else {
                                        return '<span class="layui-badge-rim">隐藏</span>';
                                    }
                                }, title: '状态'
                            },
                            {templet: '#auth-state', width: 210, align: 'center', title: '操作'}
                        ]],
                        done: function () {
                            layer.closeAll('loading');
                        }
                    });
                },
                error:function(jqXHR){
                    alert("发生错误："+ jqXHR.status);
                }
            });
           
        };
        renderTable();

 
         //监听工具条
         table.on('tool(auth-table)', function (obj) {
            var data = obj.data;
            if(obj.event === 'del'){
                active.del(data.id);
              } else if(obj.event === 'edit'){
                active.edit(data.id, data.parentId);
              } else if(obj.event === 'add'){
                active.add(data.id);
              } 
        });


                //事件
        var active = {
            del: function(id){   
            layer.confirm('确定删除吗？', function(index) {
                delData(id, index);
            });
            },
            add: function(parentId){
                updateOrAdd("添加菜单", "", parentId);
            },
            edit:function(id, parentId){
                updateOrAdd("编辑菜单", id,parentId);
            }
        }  

  
        $('#btn-expand').click(function () {
            treetable.expandAll('#auth-table');
        });

        $('#btn-fold').click(function () {
            treetable.foldAll('#auth-table');
        });   
    
        function updateOrAdd(title, id, parentId){
            layer.open({
              type: 2
              ,title: title
              ,content: 'menuForm.html#/id='+id+"/parentId="+parentId
              ,area: ['500px', '480px']
              ,btn: ['确定', '取消']
              ,yes: function(index, layero){
                var iframeWindow = window['layui-layer-iframe'+ index]
                ,submit = layero.find('iframe').contents().find("#LAY-menu-submit");
        
                //监听提交
                iframeWindow.layui.form.on('submit(LAY-menu-submit)', function(data){
                  var field = data.field; //获取提交的字段
                  //提交 Ajax 成功后，静态更新表格中的数据
                 if(field.id != undefined && field.id != ""){
                    subUpdateOrSave(field,"PUT", index);
                 } else{
                    delete field.id;
                    subUpdateOrSave(field,"POST", index);
                 }
                 
                });  
                
                submit.trigger('click');
              }
              ,success: function(layero, index){
              
              }
            })
          }
        

         //修改或者添加
        function subUpdateOrSave(data, method, index){
            layer.close(index); //关闭弹层
            data._method =method;
            admin.req({
            type: method,
            url:"/api/admin/menu",  
            data: JSON.stringify(data),   
            dataType:"json",
            contentType:'application/json;charset=utf8',
            success:function(res){
                // 表示是修改数据
                var data = res.data;
                if(res.code==200){
                    window.location.reload();//数据刷新
                }
            },
            error:function(jqXHR){
                alert("发生错误："+ jqXHR.status);
            }
            });
        }

         // 删除
         function delData(id, index) {
            layer.close(index); //关闭弹层
            admin.req({
                type:"POST",
                url:"/api/admin/menu/"+id,   
                data:{_method:"DELETE"},
                dataType:"json",
                success:function(res){
                   if(res.code == 200) {
                        layer.msg('删除成功!');
                        window.location.reload();
                   }
                },
                error:function(jqXHR){
                    alert("发生错误："+ jqXHR.status);
                }
            })
        }



    
});